package com.crealth.memcached;

import java.util.List;

import com.crealth.db.UserDb;
import com.crealth.model.UserModel;

public class UserCached {
	private static final String userKey = "user_id_";
	
	public static void deleUserCachedByID(int userID) {
		String key = userKey + userID;
		MemcachedMgr.cachedClient.delete(key);
	}
	
	public static UserModel selectUserByID(int userID) {
		String key = userKey + userID;
		Object obj = MemcachedMgr.cachedClient.get(key);
		UserModel user = null;
		if (obj == null) {
			user = UserDb.selectUserByID(userID);
			if (user != null) {
				MemcachedMgr.cachedClient.set(key, user);
			}
		}
		else {
			user = (UserModel)obj;
		}
		
		return user;
	}	
	
	public static void updateUserOnlineStatus(int userID, boolean isOnline) {
		UserDb.updateUserOnlineStatus(userID, isOnline);
		int setOnline = 0;
		if (isOnline) {
			setOnline = 1;
		}
		UserModel user = selectUserByID(userID);
		UserDb.updateUserOnlineStatus(userID, isOnline);
		user.setOnline(setOnline);
		String key = userKey + userID;
		MemcachedMgr.cachedClient.set(key, user);
	}
	
    
    public static void updateUserLoginPwd(int userID, String setNewPwd) {
    	UserDb.updateUserLoginPwd(userID, setNewPwd);
    	UserModel user = selectUserByID(userID);
		user.setLoginPwd(setNewPwd);
		String key = userKey + userID;
		MemcachedMgr.cachedClient.set(key, user);
    }
    
    public static void updateUserByUserID(UserModel userModel) {
    	int userID = userModel.getId();
    	UserDb.updateUserByUserID(userModel);
    	String key = userKey + userID;
    	MemcachedMgr.cachedClient.delete(key);
    }
    
    public static Integer updateUserMOB(UserModel user) {
    	int mob = UserModel.calcUserMOB(user.getEntryTime());
    	int userID = user.getId();
    	Integer res = UserDb.updateUserMOBByID(userID, mob);
    	if (res != null && res > 0) {
    		String key = userKey + userID;
    		Object obj = MemcachedMgr.cachedClient.get(key);
    		if (obj != null) {
    			UserModel userObj = (UserModel)obj;
    			userObj.setMOB(mob);
    			MemcachedMgr.cachedClient.set(key, userObj);
    		}
    	}
    	
    	return res;
    }
    
    public static Integer updateCompanyIDByTeamID(int teamID, int companyID) {
    	Integer res = UserDb.updateCompanyIDByTeamID(teamID, companyID);
    	if (res != null && res > 0) {
    		List<UserModel> teamUserls = UserDb.selectTeamUserByTeamID(teamID);
    		for(UserModel curUser : teamUserls) {
    			curUser.setCompanyID(companyID);
    			int userID = curUser.getId();
    	    	String key = userKey + userID;
    	    	MemcachedMgr.cachedClient.set(key, curUser);
    		}
    	}
    	
    	return res;
    }
    
    
	
}
